package inf.loansManagement;

import inf.exceptions.*;
import inf.hibernateUtils.HibernateUtil;
import inf.mediasManagement.Media;
import inf.specimensManagement.Specimen;
import inf.subscribersManagement.Subscriber;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;


/** 
 * @author Fabre, Malric
 */
public class BookingDAO {

	public static boolean save(Booking booking) {
		inf.subscribersManagement.SubscriberDAO.add(booking.getSubscriber());

		if(booking.getSpecimen() != null)
			inf.mediasManagement.MediaDAO.addSpecimen(booking.getSpecimen());
		if(booking.getMedia() != null)
			inf.mediasManagement.MediaDAO.add(booking.getMedia());

		Session session = HibernateUtil.openSession();

		try{
			session.saveOrUpdate(booking);
		} catch (Exception e) {
			System.err.println("Problem when saving");
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean remove(Booking booking){
		Session session = HibernateUtil.openSession();

		try{
			session.delete(booking);
		} catch (Exception e) {
			System.err.println("Problem when saving");
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * Gives the content of table medias in DB
	 * 
	 * @return
	 */
	public static List<Booking> getContent() {
		Session session = HibernateUtil.openSession();
		Query query = session.createQuery("from bookings");
		List<Booking> bookings = query.list();

		return bookings;
	}

	public static boolean contains(Booking booking) throws BookingExistsException {
		Session session = HibernateUtil.openSession();
		if (booking == null) throw new BookingExistsException();
		Booking l = (Booking) session.get(Booking.class, booking.getId());
		if (l == null) return false;
		else return l.equals(booking);	
	}

	/**
	 * Gets an instance of a media by ID classification
	 * 
	 * @param mediaId
	 * @return media
	 * @throws MediaExistsException 
	 * @throws DvdExistsException
	 */
	public static Booking get(long bookingId) throws BookingExistsException {
		Session session = HibernateUtil.openSession();
		Criteria criteria = session.createCriteria(Booking.class).add(Restrictions.eq("id", bookingId));
		Booking booking = (Booking)criteria.uniqueResult();
		if (booking == null) throw new BookingExistsException();
		else
			return booking;
	}

	
	/**
	 * Number of medias in DB.
	 * 
	 * @return 
	 * @throws DvdExistsException
	 */
	public long size(){
		Session session = HibernateUtil.openSession();
		Query query = session.createQuery("from bookings");
		List<Booking> bookings = query.list();
		return bookings.size();
	}
}


